package com.iplant.base.utils.tasker;

import com.iplant.base.utils.general.CalendarTool;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class TaskTimerUtils {

    private static final List<TaskTimerBase> TaskTimerList = new ArrayList<>();

    public static void AddTask(Runnable target, Calendar wMinCalendar, Calendar wMaxCalendar, int wSleepTime) {

        AddTask(target, wMinCalendar, wMaxCalendar, wSleepTime, -1);
    }


    public static void AddTask(Runnable target, int wSleepTime, int wTimes) {

        AddTask(target, CalendarTool.getDate(), CalendarTool.getDateMaxMill(), wSleepTime, wTimes);
    }

    public static void AddTask(Runnable target, Calendar wMinCalendar, Calendar wMaxCalendar) {

        AddTask(target, wMinCalendar, wMaxCalendar, 10000);
    }

    public static void AddTask(Runnable target, int wSleepTime) {

        AddTask(target, wSleepTime, -1);
    }

    public static void AddTask(Runnable target, Calendar wMinCalendar, Calendar wMaxCalendar, int wSleepTime,
                               int wTimes) {


        TaskTimerBase wTaskTimerBase = new TaskTimerBase();
        wTaskTimerBase.minCalendar = wMinCalendar;
        wTaskTimerBase.maxCalendar = wMaxCalendar;
        wTaskTimerBase.times = wTimes;
        wTaskTimerBase.sleepTime = wSleepTime;
        wTaskTimerBase.target = target;

        TaskTimerList.add(wTaskTimerBase);

        wTaskTimerBase.Run();
    }

    private static final Map<String, TaskHandleBase> TaskQueue = new HashMap<>();


    public static void AddTask(String wHandleString, Runnable target) {
        AddTask(wHandleString, target, 10000);
    }

    public static synchronized void AddTask(String wHandleString, Runnable target, int wSleepTime) {
        if (!TaskQueue.containsKey(wHandleString)) {
            TaskHandleBase wTaskHandleBase = new TaskHandleBase(wHandleString, wSleepTime);
            wTaskHandleBase.Add(target);
            TaskQueue.put(wHandleString, wTaskHandleBase);
            wTaskHandleBase.Run();
        } else {
            TaskQueue.get(wHandleString).Add(target);
        }
    }


    public static void destroy() {
        for (TaskTimerBase wTaskTimerBase : TaskTimerList) {
            wTaskTimerBase.destroy();
        }
        TaskTimerList.clear();

        for (TaskHandleBase wTaskHandleBase : TaskQueue.values()) {
            wTaskHandleBase.destroy();
        }
        TaskQueue.clear();
    }
}
